<template>
  <div class="new">
    <el-row :gutter="20" style="margin-top: 16px">
      <el-col :span="5">
        <el-input v-model="meta.title" placeholder="请输入标题" />
      </el-col>

      <el-col :span="4">
        <el-form ref="meta" :model="meta" class="demo-ruleForm">
          <el-form-item
            label="  "
            prop="ttsType"
            :rules="[{ required: true, message: '请选择' }]"
          >
            <el-select
              v-model="meta.ttsType"
              clearable
              placeholder="请选择资源"
              style="width: 87%"
            >
              <el-option
                v-for="dict in nlpList"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </el-col>

      <el-col :span="5">
        <el-select
          v-model="meta.backGroundMusic"
          clearable
          placeholder="请选择背景音乐"
          style="width: 100%"
        >
          <el-option
            v-for="dict in backGroundMusicOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-col>

      <el-col :span="5">
        <el-select
          v-model="meta.TTSSpeaker"
          clearable
          placeholder="请选择语音讲述人"
          style="width: 100%"
        >
          <el-option
            v-for="dict in TTSSpeakerOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-col>

      <el-col :span="5">
        <el-input
          v-model.number="meta.ttsRate"
          placeholder="请输入语速"
          @blur="clickBlur()"
        />
      </el-col>
    </el-row>

    <div class="content-box">
      <el-input
        v-model="meta.content"
        :rows="10"
        type="textarea"
        class="content"
        placeholder="请输入内容"
        maxlength="5000"
        show-word-limit
      />
    </div>
    <div class="button-box">
      <el-button
        type="primary"
        class="submit"
        :disabled="!meta.isSuccess"
        @click="submit(1280, 720)"
        >生成横屏</el-button
      >
      <el-button
        type="primary"
        class="submit"
        :disabled="!meta.isSuccess"
        @click="submit(720, 1280)"
        >生成竖屏</el-button
      >
    </div>

    <div class="progress">
      <div class="progress-left1">
        <el-input v-model="jobId" placeholder="请输入JobId" clearable />
      </div>
      <div class="progress-left2">
        <el-button
          type="primary"
          size="medium"
          @click="searchJobIdStatus(jobId)"
          >JobId任务状态查询</el-button
        >
      </div>
      <div v-if="!meta.isSuccess" class="progress-right1">
        {{ meta.message }}
      </div>
      <div v-if="!meta.isSuccess" class="progress-right2">
        <el-progress
          :text-inside="true"
          :stroke-width="26"
          :percentage="setItemProgress()"
          :status="setItemStatus()"
          :format="setItemText()"
        />
      </div>
    </div>

    <div v-loading="loading" class="video-box">
      <video v-show="videoJob.videoUrl" :src="videoJob.videoUrl" controls />
    </div>
  </div>
</template>

<script>
import { service } from '@/utils/request'
const RESPONSE_CODE = {
  SUCCSS: 200,
  PROCESSING: 204,
  ERROR: 500,
  VIDEO_SUCCESS: '3',
  VIDEO_FAILD: '4'
}
export default {
  data() {
    return {
      jobId: '',
      loading: false,
      myHeaders: {
        'Content-Type':
          'multipart/form-data; boundary=<calculated when request is sent>'
      },
      backGroundMusicOptions: [],
      TTSSpeakerOptions: [],
      nlpList: [],
      rules: {
        ttsType: [{ required: true, message: '请选择', trigger: 'blur' }]
      },
      meta: {
        title: '',
        content: '',
        message: '',
        isSuccess: true,
        rollTimeoutIndex: null,
        backGroundMusic: '',
        TTSSpeaker: '',
        ttsRate: '',
        percentage: 0,
        ttsType: ''
      },
      videoJob: {
        code: null,
        width: 1920,
        height: 1080,
        videoUrl: '',
        rollTimeoutIndex: null
      },
      url: '',
      fileData: '', // 文件上传数据（多文件合一）
      fileList: [], // upload多文件数组
      uploadData: {
        fieldData: {
          id: '' // 机构id,
        }
      },
      refrehList: []
    }
  },
  watch: {
    'videoJob.videoUrl': function() {
      this.loading = false
    }
  },
  created() {
    this.jobId = sessionStorage.getItem('changedJobIdValue')
    this.getDicts('fastvideo_bgm').then(response => {
      this.backGroundMusicOptions = response.data
    })

    this.getDicts('fastvideo_tts_speaker').then(response => {
      this.TTSSpeakerOptions = response.data
    })

    this.getDicts('nlp_search').then(response => {
      console.log(response.data)
      this.nlpList = response.data
    })
  },

  beforeDestroy() {
    // 在页面注销前，将定时器给关闭
    clearTimeout(this.meta.rollTimeoutIndex)
    this.meta.rollTimeoutIndex = null
  },

  methods: {
    clickBlur() {
      if (!Number.isInteger(this.meta.ttsRate)) {
        this.$message.error('请输入数字值!')
        this.meta.ttsRate = ''
        return
      }

      if (this.meta.ttsRate < -500 || this.meta.ttsRate > 500) {
        this.$message.error('请输入语速值在-500到500之间!')
        this.meta.ttsRate = ''
        return
      }
    },

    submit(width, height) {
      this.$refs.meta.validate(valid => {
        if (valid) {
          this.videoJob.width = width
          this.videoJob.height = height

          clearTimeout(this.meta.rollTimeoutIndex)
          this.meta.rollTimeoutIndex = null
          clearTimeout(this.videoJob.rollTimeoutIndex)
          this.videoJob.rollTimeoutIndex = null

          this.loading = true
          service
            .post('/textvideo/job-v2/commit', {
              title: this.meta.title,
              content: this.meta.content,
              backup3: this.meta.backGroundMusic,
              ttsSpeaker: this.meta.TTSSpeaker,
              ttsRate: this.meta.ttsRate,
              ttsType: this.meta.ttsType
            })
            .then(res => {
              if (res.code === RESPONSE_CODE.SUCCSS) {
                sessionStorage.setItem('changedJobIdValue', res.data.jobId)
                this.jobId = res.data.jobId
                // this.schedule(res.data.jobId)
                setTimeout(() => {
                  this.schedule(res.data.jobId)
                }, 1000)
              }
              if (res.code === RESPONSE_CODE.ERROR) {
                this._errorTip('任务提交失败')
              }
            })
            .catch(() => {})
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    _errorTip(text) {
      this.$notify.error({
        title: '错误',
        message: text
      })
      this.loading = false
    },

    rollSchedule() {
      this.meta.rollTimeoutIndex = setTimeout(async() => {
        this.schedule(this.jobId)
      }, 10000)
    },

    searchJobIdStatus(jobId) {
      if (jobId) {
        this.schedule(jobId)
      } else {
        this.$message.error('JobId不能为空!')
      }
    },

    schedule(jobId) {
      service
        .get(`/textvideo/job-v2/progress/${jobId}`)
        .then(res => {
          this.meta.isSuccess = res.data.isSuccess
          this.meta.message = res.data.message
          this.meta.percentage = res.data.percentage

          if (
            res.code === RESPONSE_CODE.SUCCSS &&
            res.data.isSuccess === true
          ) {
            this.videoJob.videoUrl = res.data.downloadUrl
            clearTimeout(this.meta.rollTimeoutIndex)
            this.meta.rollTimeoutIndex = null
          } else if (res.code === RESPONSE_CODE.ERROR) {
          }
          if (res.data.isSuccess === false) {
            this.rollSchedule()
          }
        })
        .catch(() => {
          // this._errorTip('资源获取失败')
        })
    },

    setItemProgress() {
      return this.meta.percentage
    },

    setItemText() {
      return () => {
        return '已完成： ' + this.meta.percentage + '%'
      }
    },

    setItemStatus() {
      return 'success'
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-form-item__content {
  margin-left: 0 !important;
}
.upload_contain {
  margin-top: 20px;
}
ul {
  list-style: none;
}
.new {
  box-sizing: border-box;
  padding: 10px;
  display: flex;
  flex-direction: column;

  .title,
  .content {
    margin-bottom: 24px;
  }
  .content-box {
    position: relative;
    margin-top: 16px;
    .content {
      margin-top: 10px;
      min-height: 200px;
    }
  }

  .button-box {
    display: flex;
  }
  .submit {
    flex: 1 1 auto;
    border-radius: 4px;
    color: #fff;
    font-size: 20px;
    padding: 4px;
    height: 42px;
    border: none;
  }
  .video-box {
    display: flex;
    justify-content: center;
    flex: 1 1 auto;
    height: 500px;
    margin-top: 30px;

    video {
      height: 100%;
      box-shadow: 3px 2px 7px #777;
    }
  }
  .progress {
    display: flex;
    flex-flow: nowrap;
    margin-top: 36px;
  }
  .progress-left1 {
    width: 20%;
  }
  .progress-left2 {
    width: 12%;
    margin-left: 36px;
  }
  .progress-right1 {
    width: 20%;
    height: 36px;
    line-height: 36px;
    font-size: 18px;
    font-size: 20px;
  }
  .progress-right2 {
    width: 35%;
  }
}
</style>
